package modLoader;
import java.net.MalformedURLException;

import java.net.URL;

import java.net.URLClassLoader;

import commands.Command;
import commands.Lmod;

public class ModLoader {
	
	public static Object newInstance(final String adres) {
		try {
			return (Object) loadClass(adres).newInstance();
		} catch (InstantiationException e) {
			throw new RuntimeException(e.getCause());
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static Class<?> loadClass(final String adres) {
		URLClassLoader tmp = new URLClassLoader(new URL[] { getClassPath() }) {
			@Override
			public synchronized Class<?> loadClass(String name)
					throws ClassNotFoundException {
				if ((adres).equals(name)) {
					return findClass(name);
				}
				return super.loadClass(name);
			}
		};
		try {
			return tmp.loadClass(adres);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static Command newCommandInstance(final String module) {
		return (Command) newInstance("commands."+module);
	}

	private static URL getClassPath() {
		String resName = Lmod.class.getName().replace('.', '/') + ".class";
		String loc = Lmod.class.getClassLoader().getResource(resName)
				.toExternalForm();
		URL cp;
		try {
			cp = new URL(loc.substring(0, loc.length() - resName.length()));
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		}
		return cp;
	}
}
